package com.caissa.springboot.starter.redis.autoconfigure;

import com.base.springboot.starter.redis.service.RedisService;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.TimeoutOptions;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author YG
 * @date 2020/8/17 下午3:48
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration{
    public RedisAutoConfiguration() {
        log.info("Starter RedisAutoConfiguration Auto Init ...");
    }

    @Value("${spring.redis.cluster.refreshPeriod:5000}")
    private long refreshPeriod;

    @Value("${spring.redis.cluster.triggersTimeout:20000}")
    private long triggersTimeout;

    @Value("${spring.redis.cluster.timeout:5000}")
    private long clusterTimeout;

    @Bean
    public RedisService setRedisService() {
        return new RedisService();
    }

    /**
     * 创建redis连接工厂类，添加高可用参数设置，
     * 覆盖默认构造逻辑 LettuceConnectionConfiguration.redisConnectionFactory()，@ConditionalOnMissingBean(RedisConnectionFactory.class)
     * @param redisProperties
     * @return LettuceConnectionFactory
     */
    @Bean
    LettuceConnectionFactory redisConnectionFactory(RedisProperties redisProperties){

        RedisProperties.Cluster clusterProperties = redisProperties.getCluster();
        if (clusterProperties == null) {
            //TODO 查找哨兵和单节点的配置 见LettuceConnectionConfiguration.createLettuceConnectionFactory()
            throw new RuntimeException("读取不到redis集群配置");
        }

        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(clusterProperties.getNodes());
        if (clusterProperties.getMaxRedirects() != null) {
            redisClusterConfiguration.setMaxRedirects(clusterProperties.getMaxRedirects());
        }
        if (redisProperties.getPassword() != null) {
            redisClusterConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
        }

        // https://github.com/lettuce-io/lettuce-core/wiki/Redis-Cluster#user-content-refreshing-the-cluster-topology-view
        ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                .enableAllAdaptiveRefreshTriggers()
                .adaptiveRefreshTriggersTimeout(Duration.ofMillis(triggersTimeout))
                .enablePeriodicRefresh(Duration.ofMillis(refreshPeriod))
                .build();

        //所有的命令超时时间
        TimeoutOptions timeoutOptions = TimeoutOptions.builder().fixedTimeout(Duration.ofMillis(clusterTimeout)).timeoutCommands().build();

        ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder().timeoutOptions(timeoutOptions)
                .topologyRefreshOptions(clusterTopologyRefreshOptions)
                .build();

        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder lettucePoolingClientConfigurationBuilder =
                LettucePoolingClientConfiguration.builder()
                .readFrom(ReadFrom.MASTER)//只从master读数据
                .poolConfig(genericObjectPoolConfig(redisProperties.getLettuce()))//增加连接池配置
                .clientOptions(clusterClientOptions);

        if (StringUtils.hasText(redisProperties.getClientName())) {
            lettucePoolingClientConfigurationBuilder.clientName(redisProperties.getClientName());
        }

        LettuceClientConfiguration lettuceClientConfiguration = lettucePoolingClientConfigurationBuilder.build();

        //redis集群构造LettuceConnectionFactory，其它方式见LettuceConnectionFactory重载方法
        return new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration);
    }

    /**
     * springboot2.x 使用LettuceConnectionFactory 代替 RedisConnectionFactory
     * application.yml配置基本信息后,springboot2.x  RedisAutoConfiguration能够自动装配
     * LettuceConnectionFactory 和 RedisConnectionFactory 及其 RedisTemplate
     *
     * @param redisConnectionFactory
     * @return
     */
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnClass(LettuceConnectionFactory.class)
    public RedisTemplate<String, Object> setRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // key也采用String的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //  使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
        Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 解决jackson2无法反序列化LocalDateTime的问题
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(Fields.DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(Fields.DEFAULT_DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(Fields.DEFAULT_TIME_FORMAT)));

        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(Fields.DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(Fields.DEFAULT_DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(Fields.DEFAULT_TIME_FORMAT)));
        objectMapper.registerModule(javaTimeModule);

        jsonRedisSerializer.setObjectMapper(objectMapper);
        // value序列化方式采用jackson
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        // hash的key也采用String的序列化方式
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // hash的value序列化方式采用jackson
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

    public static final class Fields {
        private Fields() {
        }

        /**
         * 默认日期时间格式
         */
        public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
        /**
         * 默认日期格式
         */
        public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
        /**
         * 默认时间格式
         */
        public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
    }

    /**
     * 构造apache的commons-pool
     * @param lettuce RedisProperties.Lettuce仅定义了4个参数，可根据实际情况定制参数
     * @return
     */
    private GenericObjectPoolConfig<?> genericObjectPoolConfig(RedisProperties.Lettuce lettuce) {
        GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
        RedisProperties.Pool lettucePool = lettuce.getPool();
        if (lettucePool == null) {
            return config; //全部默认
        }

        config.setMaxTotal(lettucePool.getMaxActive());
        config.setMaxIdle(lettucePool.getMaxIdle());
        config.setMinIdle(lettucePool.getMinIdle());
        config.setMaxWaitMillis(lettucePool.getMaxWait().toMillis());
        //驱逐线程的休眠时间,<=0表示没有驱逐线程运行，也就是空闲线程不会被驱逐
        //每隔timeBetweenEvictionRunsMillis毫秒检查一次连接池中空闲的连接,把空闲时间超过minEvictableIdleTimeMillis毫秒的连接断开,直到连接池中的连接数到minIdle为止
        if (lettucePool.getTimeBetweenEvictionRuns() != null) {
            config.setTimeBetweenEvictionRunsMillis(lettucePool.getTimeBetweenEvictionRuns().toMillis());
        }
        return config;
    }
}